const model = require('../../public/model/env.js');

const byteid = model.byteid();
const url = model.api_pro_url();
const key = model.key();
const appid = model.appid();
const userid = tt.getStorageSync('userid');
const truess = tt.getStorageSync('true') || 'input';

const resgua = tt.getStorageSync('resgua');
const resdata = tt.getStorageSync('resdata');
const gua_content = tt.getStorageSync('gua_content');

Page({
  data: {
    totalSeconds: 1800, // 总倒计时秒数
    minutes: 30,       // 分钟
    seconds: 0,       // 秒
    timer: null,
    // 
    getOrder: "",
    Order: '',
    order_title: '',
    imId: byteid,
    quan_num: 0,
    className: 'containerdark',
    btnup: '',
    price: '',
    coupon: '',
    total: '',
    oldprice: '39.98',
    orderid: '',
    ordertime: '...',
    orderstatus: '待付款',
    guixian: '查询中...',
    zhushu: '...',
    guize: '...',
    zhanshi: '...',
    url: "res1",
    // nickname: '你好，道友',
    pay_order_no: '正在创建中....',
    order_token: '',
    data: '',
    byteAuthorization: '',
    quan_list: 0,
    go_geren: undefined,
    //  serverTime: '2025-06-20 21:26:05', // 服务器时间
  },
  // 倒数计时
  startCountdown: function () {
    const that = this;
    that.setData({
      timer: setInterval(function () {
        if (that.data.totalSeconds > 0) {
          that.setData({
            totalSeconds: that.data.totalSeconds - 1,
            minutes: Math.floor(that.data.totalSeconds / 60),
            seconds: that.data.totalSeconds % 60
          });
        } else {
          clearInterval(that.data.timer);
          console.log('倒计时结束');
        }
      }, 1000)
    });
  },
  calculateTimeDifference: function (time) {
    const time = time;
    const serverTimeStr = time;
    const serverTime = new Date(serverTimeStr.replace(/-/g, '/')); // 将日期字符串转换为Date对象
    serverTime.setMinutes(serverTime.getMinutes() + 30); // 将serverTime加30分钟

    const currentTime = new Date(); // 获取当前时间

    // 计算时间差（以毫秒为单位）
    let difference = serverTime - currentTime;

    // 将时间差转换为秒
    difference = Math.abs(Math.floor(difference / 1000));

    if (serverTime < currentTime) {
      this.setData({
        orderstatus: '订单已超时',
        totalSeconds: 0,
        minutes: 0,
        seconds: 0
      });
    } else {
      // 计算相差的分钟和秒
      const minutes = Math.floor(difference / 60);
      const seconds = difference % 60;
      const differences = difference;
      this.setData({
        totalSeconds: differences,
        minutes: minutes,
        seconds: seconds
      });
      console.log(`相差 ${minutes} 分钟 ${seconds} 秒`);
    }
  },

  onUnload: function () {
    clearInterval(this.data.timer);
  },
  // 关闭倒计时
  imCallback(e) {
    console.log("跳转IM客服成功", e.detail);
  },
  onimError(e) {
    console.log("拉起IM客服失败", e.detail);
  },

  onLoad: function (quan) {

    // console.log("onLoad", tt.getStorageSync('userid'));
    console.log("onLoad", quan.quan);
    const quan_list = quan.quan;
    // 假设的 e 对象结构

    const e = undefined;
    // 调用 quan_delete 函数
    if (quan_list == 701) {
      this.quan_delete(e).then((modifiedE) => {
        // console.log("111111111111111999999999", modifiedE);
        if (modifiedE == 701) {
          const quan_os = 701;
          this.fasongorder(quan_os);
        }
      });

    }
    if (quan_list == 0) {
      const quan_os = 0;
      this.fasongorder(quan_os);
    }





    const that = this;


    // 判断是否是ios系统
    tt.getSystemInfo({

      success(res) {
        if (res.platform == "ios")
          that.setData({
            getOrder: '',
            Order: '',
            btnup: 'IOS无法支付',
            order_title: 'IOS无法支付',
          })
        console.log("getSystemInfo 调用成功", res.platform);
      },
      fail(err) {
        console.log("getSystemInfo 调用失败", err);
      },

    });



    if (truess == "aboutindex" || truess == "about") {
      this.setData({
        getOrder: '',
        Order: '',
        btnup: '非支付订单',
        order_title: '非支付订单',
      })
    } else if (truess == "input") {
      this.setData({
        getOrder: 'getOrderPayment',
        Order: 'requestOrder',
        btnup: '测算支付',
        order_title: '周易测算订单详情',

      })
    }



    console.log(resgua);
    // let guanumber = resgua.name;
    console.log(userid);
    // console.log(nickname);
    this.setData({
      // nickname: nickname,
      guixian: resgua.name,
      zhushu: resgua.yaobian,
      guize: `${resgua.name}。${resdata}。`,
      zhanshi: gua_content,
    });
    if (resgua.name == undefined) {
      this.setData({
        guize: '暂无数据,请返回首页重测试',
        zhanshi: '暂无数据,请返回首页重测试',
      });
    }

    this.startCountdown();
  },

  // 查询订单，是否支付成功
  tijiaoorderchaxun: function () {
    const requestUrl = `${url}/index.php/api/order_query.php`;
    const options = {
      url: requestUrl,
      data: {
        appid: appid,
        key: key,
        user_id: userid,
        outOrderNo: this.data.pay_order_no,
      },
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      dataType: 'json',
    };
    // console.log(options);
    tt.request({
      ...options,
      success: (res) => {
        if (res.data.code == 200) {
          navigateTo({
            url: '../res/res?orderid=' + this.data.pay_order_no + '&order_thing=' + this.data.zhanshi + '&order_gua=' + this.data.guixian + '&order_bianyao=' + this.data.zhushu + '&order_p=202',
          });
        } else {
          tt.showToast({
            title: "订单查询失败",
            icon: 'none',
            duration: 2000
          });
        }
      }

    });
  },

  // 拉起收银台
  tijiaoorder: function () {
    console.log(this.data.orderid);

    tt[this.data.getOrder]({
      orderId: this.data.orderid, // 替换为抖音开放平台内部的交易订单号
      // orderId: 'motb75109979572740610962532',
      success: (res) => {
        // 
        const requestUrl = `${url}/index.php/api/order_query.php`;
        const options = {
          url: requestUrl,
          data: {
            appid: appid,
            key: key,
            user_id: userid,
            outOrderNo: this.data.pay_order_no,
          },
          method: 'POST',
          header: {
            'content-type': 'application/json'
          },
          dataType: 'json',
        };
        console.log(options);
        tt.request({
          ...options,
          success: (res) => {
            console.log(res);
            this.setData({
              showModal: true,
            });
          }

        });
        // 
        console.log("支付成功", res);
        tt.showToast({
          icon: "success",
          title: "支付成功",
        });
        tt.navigateTo({
          url: '../res/res?orderid=' + this.data.pay_order_no + '&order_thing=' + this.data.zhanshi + '&order_gua=' + this.data.guixian + '&order_bianyao=' + this.data.zhushu + '&order_p=202',
        });
      },
      fail: (res) => {
        this.setData({
          showModal: true,
        });
        console.error("支付失败", res);
        const { errNo, errMsg } = res;
        tt.showToast({
          icon: "fail",
          title: "支付失败",
        });
      },
    });
  },

  quan_delete: function (e) {
    const requestUrlquandelete = `${url}/index.php/api/quan_delete.php`;
    const quandeletes = {
      url: requestUrlquandelete,
      data: {
        // appid: appid,
        key: key,
        user_id: tt.getStorageSync('userid'),
      },
      method: 'GET',
      header: {
        'content-type': 'application/json'
      },
      dataType: 'json',
    };
    console.log(quandeletes);
    return new Promise((resolve, reject) => {
      tt.request({
        ...quandeletes,
        success: (res) => {
          const data = res.data;

          if (data.code == 200) {
            e = 701;
            console.log(data);
            tt.showToast({
              title: '使用优惠券成功',
              icon: 'none',
              duration: 1000,
              success: function (res) {
                console.log(res);
              }
            });
            resolve(e);
          } else {
            // console.log(data);
            e = 0;
            tt.showToast({
              title: '使用优惠券失败',
              icon: 'none',
              duration: 1000,
              success: function (res) {
                console.log(res);
              }
            });
            resolve(e);
          }

        },
        fail: (err) => {
          console.log(err);
          reject(err);
        }

      });
    })

    // 
  },
  go_geren() {
    tt.navigateTo({
      url: '../my/my',
    });
  },
  fasongorder: function (quan_os) {
    const quan_os = quan_os;
    const requestUrl = `${url}/index.php/api/byteAuthorization.php`;
    const options = {
      url: requestUrl,
      data: {
        appid: appid,
        key: key,
        user_id: userid,
        quan_list: quan_os, // 优惠券列表
      },
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      dataType: 'json',
    };
    console.log(options);
    tt.request({
      ...options,
      success: (res) => {
        console.log(res.data);
        if (res.data.code == 200) {
          // 
          if (res.data.total_fee / 100 < 9.98) {
            this.setData({
              showCoupon: true,
              jian: '- 6.00元',

            });
          } else {
            this.setData({
              showCoupon: false,
              jian: '没有优惠券',
              go_geren: false,

            });
          }



          this.setData({
            data: res.data.data,
            byteAuthorization: res.data.byteAuthorization,
            pay_order_no: res.data.pay_order_no,
            total: res.data.total_fee / 100,
            price: res.data.total_fee / 100,
            ordertime: res.data.order_date,
          });
          // 
          const userid = tt.getStorageSync('userid');

          tt[this.data.Order]({
            data: this.data.data, // 开发者服务端返回的data示例
            byteAuthorization: this.data.byteAuthorization, // 开发者服务端返回的byteAuthorization
            success: (res) => {
              this.setData({
                orderid: res.orderId,
              });
              const { orderId } = res;
              console.log("orderId", orderId); // 抖音开放平台内部的交易订单号
              const requestUrl = `${url}/index.php/api/save_order_id.php`;
              const options = {
                url: requestUrl,
                data: {
                  appid: appid,
                  key: key,
                  user_id: userid,
                  order_id: orderId,
                  pay_order_no: this.data.pay_order_no,
                },
                method: 'POST',
                header: {
                  'content-type': 'application/json'
                },
                dataType: 'json',
              };

              tt.request({
                ...options,
                success: (res) => {
                  console.log(res.data);
                }
              })
            },
            fail: (res) => {
              const { errLogId, errMsg, errNo } = res;
              console.log("errNo:", errNo);
              console.log("errMsg:", errMsg);
            },
          });
          // 结束订单请求创建
        }
        else if (res.data.code == 202) {
          this.calculateTimeDifference(res.data.data[0].order_date);
          console.log(res.data);
          if (res.data.data[0].total_fee / 100 < 9.98) {
            this.setData({
              showCoupon: true,
              jian: '- 6.00元',

            });
          } else {
            this.setData({
              showCoupon: false,
              jian: '没有优惠券',
              go_geren: true,

            });
          }
          this.setData({
            orderid: res.data.data[0].order_id,
            total: res.data.data[0].total_fee / 100,
            price: res.data.data[0].total_fee / 100,
            pay_order_no: res.data.data[0].pay_order_no,
            ordertime: res.data.data[0].order_date,

          });

        }


      }

    });
  }

})